package no21.thread;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 测试管道(一种阻塞队列的工作模式)
 * 
 * @author gao
 * 
 */

class Sender implements Runnable {
	private Random rand = new Random(47);
	private PipedWriter out = new PipedWriter();

	public PipedWriter getPipedWriter() {
		return out;
	}

	@Override
	public void run() {
		for (char c = 'A'; c <= 'Z'; c++) {
			try {
				out.write(c);
				TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println(e.getMessage());
			}
		}
	}
}

class Receiver implements Runnable {
	private PipedReader in;

	public Receiver(Sender sender) throws IOException {
		in = new PipedReader(sender.getPipedWriter());
	}

	@Override
	public void run() {
		try {
			while (true) {
				System.out.println("Read: " + (char) in.read() + ", ");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}

}

public class PipedIO {
	public static void main(String[] args) throws Exception {
		// new 两个command
		Sender sender = new Sender();
		Receiver receiver = new Receiver(sender);
		// 交给执行器执行
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(sender);
		exec.execute(receiver);

		TimeUnit.MILLISECONDS.sleep(10);
		// 顺序关闭
		exec.shutdownNow();
		System.out.println("shutdown over");
	}
}
